const express = require('express');
const cors = require('cors');
const axios = require('axios');

const app = express();
const port = 3000;

// 允许跨域
app.use(cors());
app.use(express.json());

// 基础URL
const REGISTER_BASE_URL = 'http://39.108.161.49:10000'; // 注册接口的基础地址
const API_BASE_URL = 'http://120.78.19.227:25896'; // 其他接口的基础地址
// const SIGN_BASE_URL = 'http://120.46.20.35:7989'; // 签名接口的基础地址
const SIGN_BASE_URL = 'http://47.92.243.14:9899'; // 签名接口的基础地址

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000
});

// 从Authorization头中提取token
const getTokenFromAuth = (authHeader) => {
  if (!authHeader) return null;
  // 格式可能是 "Bearer token" 或直接是token
  const parts = authHeader.split(' ');
  return parts.length > 1 ? parts[1] : parts[0];
};

// 注册接口
app.post('/api/register', async (req, res) => {
  try {
    const response = await axios.post(`${REGISTER_BASE_URL}/write_off/cy/register`, req.body);
    res.json(response.data);
  } catch (error) {
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 登录接口
app.post('/api/login', async (req, res) => {
  try {
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/channel/login`, req.body);
    res.json(response.data);
  } catch (error) {
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 获取sessionId接口
app.post('/api/getSessionId', async (req, res) => {
  try {
    console.log('getSessionId headers:', req.headers);
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    console.log('getSessionId token:', token);
    
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/getSessionId`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('getSessionId error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 查询积分接口
app.post('/api/getPoints', async (req, res) => {
  try {
    console.log('getPoints headers:', req.headers);
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    console.log('getPoints token:', token);
    
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/getPointsAndAuth`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('getPoints error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 发送绑定验证码接口
app.post('/api/sendBindCode', async (req, res) => {
  try {
    console.log('sendBindCode headers:', req.headers);
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    console.log('sendBindCode token:', token);
    
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/quickToBinding`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('sendBindCode error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 绑定账号接口
app.post('/api/bindAccount', async (req, res) => {
  try {
    console.log('bindAccount headers:', req.headers);
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    console.log('bindAccount token:', token);
    
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/bindInfo`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('bindAccount error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 自动下单接口
app.post('/api/autoOrder', async (req, res) => {
  try {
    console.log('autoOrder headers:', req.headers);
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    console.log('autoOrder token:', token);
    
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/orderV3`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('autoOrder error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 自定义下单接口
app.post('/api/customOrder', async (req, res) => {
  try {
    console.log('customOrder headers:', req.headers);
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    console.log('customOrder token:', token);
    
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/choiceOrder`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('customOrder error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 下单接口
app.post('/api/orderPay', async (req, res) => {
  try {
    console.log('orderPay headers:', req.headers);
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    console.log('orderPay token:', token);
    
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/orderPayV3`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('orderPay error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 重发验证码接口
app.post('/api/resendOrderSms', async (req, res) => {
  try {
    console.log('resendOrderSms headers:', req.headers);
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    console.log('resendOrderSms token:', token);
    
    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/orderSMS`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('resendOrderSms error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 查询手机归属地
app.post('/api/checkPhone', async (req, res) => {
  try {
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);

    const response = await axios.post(`${API_BASE_URL}/jfcy-service/v3/checkPhone`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('resendOrderSms error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 获取签名接口
app.post('/api/getSign', async (req, res) => {
  try {
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/getsign`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 获取用户优惠券列表接口
app.post('/api/v3/marketing/favor/users/:openid/coupons', async (req, res) => {
  try {
    console.log('getUserCoupons headers:', req.headers);
    
    // 先获取签名
    /* const signResponse = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/getsign`, req.body, {
      headers: {
        'Authorization': `Bearer ${getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization'])}`
      }
    });
    
    if (!signResponse.data || !signResponse.data.data) {
      throw new Error('获取签名失败');
    }
      const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
      console.log('getSessionId token:', token);

      console.log('signResponse1111:', signResponse.data.data); */
    const { openid } = req.params;
    const response = await axios.post(`https://api.mch.weixin.qq.com/v3/marketing/favor/users/${openid}/coupons`, req.body, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        // 'Authorization': signResponse.data.data,
        'Authorization': req.headers['authorization'] || req.headers['Authorization']
      }
    });
    
    res.json(response.data);
  } catch (error) {
    console.error('getUserCoupons error:', error.response);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 获取用户OpenId接口
app.post('/api/getOpenId', async (req, res) => {
  try {
    const { appid, secret, code, grant_type } = req.body;
    const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=${grant_type}`;
    
    const response = await axios.get(url, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
    });
    
    res.json(response.data);
  } catch (error) {
    console.error('getOpenId error:', error.response);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 保存数据接口
app.post('/api/savedata', async (req, res) => {
  try {
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/savedata`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('savedata error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 阻止电话号码接口
app.post('/api/blockphone', async (req, res) => {
  try {
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/blockphone`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('blockphone error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 获取图片地址
app.post('/api/getpic', async (req, res) => {
  try {
    const token = getTokenFromAuth(req.headers['authorization'] || req.headers['Authorization']);
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/getpic`, req.body, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    res.json(response.data);
  } catch (error) {
    console.error('blockphone error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 添加手机号接口
app.post('/api/addphone', async (req, res) => {
  try {
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/addphone`, req.body, {
    });
    res.json(response.data);
  } catch (error) {
    console.error('blockphone error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});
// 手机积分添加接口
app.post('/api/updatephone', async (req, res) => {
  try {
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/updatephone`, req.body, {
    });
    res.json(response.data);
  } catch (error) {
    console.error('blockphone error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});
// 未下单错误原因接口
app.post('/api/erphone', async (req, res) => {
  try {
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/erphone`, req.body, {
    });
    res.json(response.data);
  } catch (error) {
    console.error('blockphone error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});
// 未下单错误原因接口
app.post('/api/erphone', async (req, res) => {
  try {
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/erphone`, req.body, {
    });
    res.json(response.data);
  } catch (error) {
    console.error('blockphone error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 获取银行卡渠道ID接口
app.get('/api/getyhkq', async (req, res) => {
  try {
    const response = await axios.get(`${SIGN_BASE_URL}/index.php/api/index/getyhkq`);
    res.json(response.data);
  } catch (error) {
    console.error('getyhkq error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});
// 获取ip
app.get('/api/getip', async (req, res) => {
  try {
    const response = await axios.get(`${SIGN_BASE_URL}/index.php/api/index/getip`);
    res.json(response.data);
  } catch (error) {
    console.error('getyhkq error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 新用户输入验证码并且跳转到第二页时调用接口
app.post('/api/uptotwo', async (req, res) => {
  try {
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/uptotwo`, req.body, {
    });
    res.json(response.data);
  } catch (error) {
    console.error('blockphone error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});
// 验证是否输入验证码接口
app.post('/api/ifyz', async (req, res) => {
  try {
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/ifyz`, req.body, {
    });
    res.json(response.data);
  } catch (error) {
    console.error('blockphone error:', error.response?.data);
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

// 添加非移动手机接口
app.post('/api/addotherphone', async (req, res) => {
  try {
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/addotherphone`, req.body, {
    });
    res.json(response.data);
  } catch (error) {
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});
// 是否点击银行券接口
app.post('/api/clickyh', async (req, res) => {
  try {
    const response = await axios.post(`${SIGN_BASE_URL}/index.php/api/index/clickyh`, req.body, {
    });
    res.json(response.data);
  } catch (error) {
    res.status(500).json(error.response?.data || { message: '服务器错误' });
  }
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
}); 